import enum
import json
import os
import sys

from absl import app, flags

class SourceEnum(enum.IntEnum):
  EXCHANGE = 1
  DUMMY = 2

def get_source(ts):
  return SourceEnum(ts % 10).name

def get_exchanges_from_conf(driver):
  exchanges = []
  with open(driver) as fd:
    driver_conf = json.load(fd)
    ex_infos = driver_conf['order']['exchanges']
    for info in ex_infos.values():
      mea = info['mea']
      symbols = []
      # TODO(daniel): handle native symbol & regular product like "(.*)-USDT"
      products = info['products']
      if 'norms' in products:
        symbol_type = 'NORM'
        symbols = products['norms']
      exchange = {
        "mea": mea,
        "symbols": symbols,
        "type": symbol_type,
      }
      exchanges.append(exchange)
  return exchanges


def get_pi_ready_symbols_by_mea(mea):
  norm_symbols = []
  native_symbols = []
  pi_json = "data/coin2/product_info/%s.json" % mea
  if os.path.exists(pi_json):
    with open(pi_json) as fd:
      data = json.load(fd)
      pis = data['product_infos']
      for pi in pis:
        if 'EXCHANGE' == get_source(pi['fetched_time']):
          norm_symbols.append(pi['symbol'])
          native_symbols.append(pi['native_symbol'])
  return norm_symbols, native_symbols


def check_if_pi_is_ready(exchange):
  mea = exchange['mea']
  symbols = exchange['symbols']
  symbol_type = exchange['type']
  norm_symbols, native_symbols = get_pi_ready_symbols_by_mea(mea)
  if symbol_type == "NORM":
    return len(set(symbols) - set(norm_symbols)) == 0
  elif symbol_type == "NATIVE":
    return len(set(symbols) - set(native_symbols)) == 0
  return True

def check_pi_from_driver_config(driver):
  if driver is None:
    return False
  exchanges = get_exchanges_from_conf(driver)
  if len(exchanges) == 0:
    print("Could not find MEA from driver config")
    return False
  for exchange in exchanges:
    if not check_if_pi_is_ready(exchange):
      return False
  return True


def main(_):
  try:
    if check_pi_from_driver_config(flags.FLAGS.driver):
      print("SUCCESS")
    else:
      print("FAIL")
  except:
    import traceback
    traceback.print_exc()
    print("FAIL")


if __name__ == '__main__':
  flags.DEFINE_string('driver', None, 'driver config')
  app.run(main)
